/*
 * Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.
 *
 * https://www.mall4j.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.api.controller;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.dto.PostDTO;
import com.yami.shop.bean.model.Comment;
import com.yami.shop.bean.model.HotTopics;
import com.yami.shop.bean.param.CommentParam;
import com.yami.shop.bean.param.CreatePostParam;
import com.yami.shop.bean.param.PostsQuery;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.security.api.util.SecurityUtils;
import com.yami.shop.service.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Stream;

/**
 * @author lanhai
 */
@RestController
@RequestMapping("/p/social/post")
@Tag(name = "社区帖子接口")
@Slf4j
@AllArgsConstructor
public class SocialPostController {

    private final PostService postService;
    private final LikeService likeService;
    private final CommentService commentService;

    /**
     * x-file-storage
     */
    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private HotTopicService hotTopicsService;

    @Autowired
    private TopicParticipationService topicParticipationService;

    @GetMapping("/page")
    @Operation(summary = "分页获取帖子列表")
    @Parameters({
            @Parameter(name = "topic", description = "话题过滤"),
            @Parameter(name = "page", description = "页码"),
            @Parameter(name = "pageSize", description = "页大小")
    })
    public ServerResponseEntity<IPage<PostDTO>> getPostPage(PageParam page, HotTopics topic) {
        log.info("请求参数：{}",topic);
        return ServerResponseEntity.success(hotTopicsService.getTopicWithPosts(page, topic));
    }

    @PostMapping
    @Operation(summary = "创建新帖子")
    public ServerResponseEntity<Long> createPost(@RequestBody CreatePostParam param) {
        log.info("请求参数：{}",param);
        param.setUserId(SecurityUtils.getUser().getUserId());
        Long postId = postService.createPost(param);
        /**
         * 新添加动态时，需要关联相关的话题
         */
        topicParticipationService.addTopicWithPost(param.getTopicId(), postId);
        return ServerResponseEntity.success(postId);
    }

    /**
     * 点赞
     * @param postId
     * @param like
     * @return
     */
    @PostMapping("/{postId}/like")
    @Operation(summary = "点赞")
    public ServerResponseEntity<Integer> toggleLike(
            @Parameter(description = "帖子ID")
            @PathVariable String postId,
            @RequestParam @Parameter(description = "点赞状态") boolean like) {
        int newStatus = likeService.likeOrUnlike(postId, SecurityUtils.getUser().getUserId(),like);
        log.info("点赞状态：{}",like);
        return ServerResponseEntity.success(newStatus);
    }

    /**
     * 取消点赞
     * @param postId
     * @param userId
     * @return
     */
    @PostMapping("/unlike")
    @Operation(summary = "取消点赞帖子")
    public ResponseEntity<String> unlike(@RequestParam String postId, @RequestParam String userId) {
        int result = likeService.likeOrUnlike(postId, userId, false);
        return result == 1 ? ResponseEntity.ok("取消成功") : ResponseEntity.ok("未点赞过");
    }

    /**
     * 获取点赞数量
     * @param postId
     * @return
     */
    @GetMapping("/likes/count")
    @Operation(summary = "获取点赞数量")

    public ResponseEntity<Long> getLikesCount(@RequestParam Long postId) {
        return ResponseEntity.ok(likeService.getLikesCount(postId));
    }




    @GetMapping("/{postId}/comment")
    @Operation(summary = "获取评论列表")
    public ServerResponseEntity<Stream<Comment>> getComments(
            @Parameter(description = "帖子ID") @PathVariable Long postId) {
        return ServerResponseEntity.success(commentService.getCommentsByPost(postId));
    }

    @PostMapping("/{postId}/comment")
    @Operation(summary = "添加评论")
    public ServerResponseEntity<Long> addComment(@PathVariable Long postId, @RequestBody CommentParam param) {
        param.setUserId(SecurityUtils.getUser().getUserId());
        param.setPostId(postId);
        log.info("评论内容{}" + param.getContent());
        Long commentId = commentService.addComment(param);
        return ServerResponseEntity.success(commentId);
    }

    /**
     * TODO 文件上传调用公共接口
     *
     * @PostMapping("/upload/image")
     * @Operation(summary = "上传图片文件")
     * public ServerResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
     * String url = postService.uploadFile(file, FileType.IMAGE);
     * return ServerResponseEntity.success(url);
     * }
     * @PostMapping("/upload/video")
     * @Operation(summary = "上传视频文件")
     * public ServerResponseEntity<String> uploadVideo(@RequestParam("file") MultipartFile file) {
     * String url = postService.uploadFile(file, FileType.VIDEO);
     * return ServerResponseEntity.success(url);
     * }
     **/
    @PostMapping("/upload")
    public ServerResponseEntity uploadFile(MultipartFile file) throws Exception {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return ServerResponseEntity.success("文件为空");
        }

        // 获取当前日期并格式化为年/月/日形式
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));

        // 获取文件扩展名
        String extName = FileUtil.extName(file.getOriginalFilename());

        // 上传文件到OSS服务
        log.info("开始上传文件，文件信息: {}", file);
        FileInfo fileInfo = fileStorageService.of(file)
                .setPath(datePath.replace("/", "/")) // 设置存储路径（仅日期部分）
                .setName(file.getOriginalFilename()) // 使用原始文件名上传
                .upload();

        // 获取OSS返回的完整文件路径
        String ossFullPath = fileInfo.getUrl(); // 假设FileInfo类提供了getFullPath()方法

        // 构建保存到数据库的地址
        String databasePath = ossFullPath;

        // 日志输出保存到数据库的路径
        log.info("保存到数据库的文件路径: {}", databasePath);

        // 返回保存到数据库的路径
        return ServerResponseEntity.success(databasePath);
    }

    @DeleteMapping
    @Operation(summary = "删除帖子")
    public ServerResponseEntity<Void> deletePost(@Parameter(description = "帖子ID") @RequestParam Long postId) {
        postService.deletePost(postId, SecurityUtils.getUser().getUserId());
        return ServerResponseEntity.success();
    }

    /**
     * 获取话题列表
     */
    @GetMapping("/topics")
    @Operation(summary = "获取话题列表")
    public ServerResponseEntity<List<HotTopics>> getTopics() {
        return ServerResponseEntity.success(hotTopicsService.getAllTopic());
    }

    /**
     * 添加话题
     */
    @PostMapping("/topics")
    @Operation(summary = "添加话题")
    public ServerResponseEntity<Void> addTopic(@RequestBody HotTopics hotTopics) {
        hotTopicsService.save(hotTopics);
        return ServerResponseEntity.success();
    }
}
